#!/bin/bash

# SmartInput 快速SSL设置脚本
# 自动生成证书并提供安装指导

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

print_message $BLUE "🚀 SmartInput 快速SSL设置"
print_message $BLUE "=========================="

# 检查是否已有证书
if [ -f "$PROJECT_ROOT/cert.pem" ] && [ -f "$PROJECT_ROOT/key.pem" ]; then
    print_message $YELLOW "⚠️  检测到现有证书文件"
    read -p "是否要重新生成证书？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_message $GREEN "✅ 使用现有证书"
        CERT_EXISTS=true
    else
        print_message $YELLOW "🔄 删除现有证书..."
        rm -f "$PROJECT_ROOT"/*.pem
        rm -f "$PROJECT_ROOT/server"/*.pem
        rm -rf "$PROJECT_ROOT/certs"
        CERT_EXISTS=false
    fi
else
    CERT_EXISTS=false
fi

# 生成证书
if [ "$CERT_EXISTS" != true ]; then
    print_message $YELLOW "🔑 生成新的SSL证书..."
    
    # 确保证书生成脚本存在且可执行
    CERT_SCRIPT="$PROJECT_ROOT/scripts/create-ssl-certificates.sh"
    if [ ! -f "$CERT_SCRIPT" ]; then
        print_message $RED "❌ 证书生成脚本不存在: $CERT_SCRIPT"
        exit 1
    fi
    
    chmod +x "$CERT_SCRIPT"
    "$CERT_SCRIPT"
fi

# 获取本机IP地址
print_message $YELLOW "🌐 检测网络配置..."

# 获取局域网IP
LOCAL_IP=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'src \K\S+' || echo "未知")
if [ "$LOCAL_IP" = "未知" ]; then
    LOCAL_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "192.168.1.100")
fi

print_message $GREEN "✅ 检测到本机IP: $LOCAL_IP"

# 测试证书
print_message $YELLOW "🧪 测试SSL证书..."

# 启动临时测试服务器
TEMP_SERVER_PID=""
start_test_server() {
    cd "$PROJECT_ROOT"
    if command -v node &> /dev/null && [ -d "server/node_modules" ]; then
        print_message $BLUE "启动Node.js测试服务器..."
        cd server
        npm start > /dev/null 2>&1 &
        TEMP_SERVER_PID=$!
        cd "$PROJECT_ROOT"
    else
        print_message $BLUE "启动OpenSSL测试服务器..."
        openssl s_server -cert cert.pem -key key.pem -port 3001 -HTTP > /dev/null 2>&1 &
        TEMP_SERVER_PID=$!
    fi
    
    # 等待服务器启动
    sleep 3
}

stop_test_server() {
    if [ -n "$TEMP_SERVER_PID" ]; then
        kill $TEMP_SERVER_PID 2>/dev/null || true
        wait $TEMP_SERVER_PID 2>/dev/null || true
    fi
}

# 启动测试服务器
start_test_server

# 测试连接
test_url() {
    local url=$1
    local name=$2
    
    if curl -k -s --connect-timeout 5 "$url" > /dev/null 2>&1; then
        print_message $GREEN "✅ $name 连接成功"
        return 0
    else
        print_message $RED "❌ $name 连接失败"
        return 1
    fi
}

print_message $BLUE "测试HTTPS连接..."
test_url "https://localhost:3001" "localhost"
test_url "https://127.0.0.1:3001" "127.0.0.1"
test_url "https://$LOCAL_IP:3001" "$LOCAL_IP"

# 停止测试服务器
stop_test_server

print_message $GREEN "🎉 SSL证书设置完成！"
print_message $BLUE "=========================="

print_message $YELLOW "📋 下一步操作："
echo ""
echo "1. 安装CA根证书到您的设备："
echo "   文件位置: $PROJECT_ROOT/certs/ca-cert.pem"
echo ""
echo "2. 桌面设备（Windows/macOS/Linux）："
echo "   - 双击 ca-cert.pem 文件并按提示安装"
echo "   - 或查看详细指南: CERT_INSTALLATION_GUIDE.md"
echo ""
echo "3. 手机设备："
echo "   - Android: 发送ca-cert.pem到手机，设置→安全→安装证书"
echo "   - iOS: 通过邮件发送证书，设置→通用→证书信任设置"
echo ""
echo "4. 启动SmartInput服务器："
echo "   ./start.sh"
echo ""
echo "5. 验证连接："
echo "   浏览器访问: https://localhost:3001/health"
echo "   手机访问: https://$LOCAL_IP:3001/health"

print_message $BLUE "📖 详细安装指南："
echo "查看 CERT_INSTALLATION_GUIDE.md 获取完整的安装说明"

print_message $YELLOW "💡 故障排除："
echo "如果仍有连接问题："
echo "- 确保防火墙允许端口3001"
echo "- 重启浏览器和SmartInput服务器"
echo "- 运行: ./test-https-connections.js 进行诊断" 